<?php

namespace app\members\controller;

use app\common\traits\ApiResponseTrait;
use app\middleware\AuthMemberMiddleware;
use GatewayClient\Gateway;
use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\Request;

/**
 * 主页
 */
class Index
{
    use ApiResponseTrait;

    protected $middleware = [AuthMemberMiddleware::class=>
        ['except'=>['login','qr','miniauth','records']]
    ];


    // 验证登录
    public function miniauth(){
        // 验证登录用的 只有mini会用
        if( !empty(request()->post('params')) ){

            $p = explode('=',request()->post('params'))[1];
            Session::setId($p);
            Session::Init();
            $info = Session::get('member_info');

            if( !empty( $info ) ){
                if( !empty(request()->post('cuid') ) ){
                    $toid = request()->post('cuid');
                    Db::name('im_visitors_info')
                        ->where(['vsid'=>$info['vsid']])
                        ->where('cuid','<>',$toid)->update(['cuid'=>$toid]);
                }

                return $this->responseSuccess(['data'=>$info]);
            }
        }
        return $this->responseFails();
    }

    public function history()
    {

        $userSwitch = goalong_hook('user_auth_switch',[],1);

        if( !empty(request()->get('sid') ) ){
            View::assign('sid',request()->get('sid'));
        }

        // 判断是否登录
        $member_info = Session::get('member_info');

        // 未登录跳转到登录页面
        if( empty( $member_info ) )
            return redirect('login');

        $visitor = Db::name('im_visitors')
            ->field('vi.cuid')
            ->alias('v')
            ->join('im_visitors_info vi','v.id=vi.vsid')
            ->where('v.uid',$member_info['uid'])->findOrEmpty();

        // 没有数据了
        if( empty( $visitor ) ){
            Session::delete('member_info');
            return redirect('login');
        }

        $is_export = goalong_hook('export_records_switch',[],1);

        View::assign('toid',$visitor['cuid']);
        View::assign('user_auth',$userSwitch);
        View::assign('username',$member_info['username']);
        View::assign('nick',$member_info['nick']);
        View::assign('uid',$member_info['uid']);
        View::assign('fromid',$member_info['vsid']);
        View::assign('is_export',$is_export);

        return View::fetch();
    }

    public function qr(Request $r){

        if( !$r->isAjax() )
            return ;

        $ofromid = $r->get('ofromid',0,'intval') ;
        $cuid = $r->get('cuid',0,'intval');
        $params = [] ;

        if( $ofromid && $cuid ){
            $params = ['id'=>$cuid.'_'.$ofromid];
        }
        $qrcode = goalong_hook('get_auth_qr',$params,1);

        return $qrcode ? $this->responseSuccess($qrcode) : $this->responseFails('获取失败');
    }

    // 登录页面
    public function login(){

        $userSwitch = goalong_hook('user_auth_switch',[],1);
        $wechatSwitch = goalong_hook('wechat_auth_switch',[],1);

        //dump(goalong_hook('user_login_sms',[],1) );
        if( !$userSwitch && !$wechatSwitch ){
            exit('插件已关闭');
        }

        $typeTransform = [
            'email'=>['value'=>0,'name'=>'邮箱'],
            'mobile'=>['value'=>1,'name'=>'手机'],
        ];

        //$wechatConfig = goalong_hook('wechat_auth_switch' , [],1);
        $userConfig = goalong_hook('user_auth_config',[],1);

        $types = [];
        if( $userConfig ){
            $array = explode(',',$userConfig['type']);
            foreach( $array as $k => $v ){
                $value['value'] = $typeTransform[$v]['value'];
                $value['checked'] = ( $k == 0 ? 'checked' : '' );
                $value['name'] = $typeTransform[$v]['name'];
                $types[$k] = $value;
            }
        }

        if( $wechatSwitch ){
            array_push($types,[
                'value'=>2,
                'checked'=>count($types) > 0 ? '' : 'checked',
                'name'=>'扫码',
            ]);
        }

        View::assign('types',$types);
        View::assign('sid',Session::getId());
        return View::fetch();
    }


    public function logout(){
        //if( !empty( request()->get('sid') ) ){
            //Session::setId(request()->get('sid'));
            //Session::Init();
        //}
        //$member_info = Session::get('member_info');

        Session::delete('member_info');
        // 退出登录以后读取访客信息，数据重置一下
        return $this->responseSuccess('注销成功');
    }


    /**
     * 会员 加载历史消息
     */
    public function records()
    {
        $r = request() ;
        if ($r->isAjax()) {
            $post = $r->post();
            $record = Db::name('im_record')
                ->where("send = {$post['fromid']} AND receive = {$post['toid']}")
                ->whereOr("send = {$post['toid']} AND receive = {$post['fromid']}")
                ->whereOr("source_cuid = {$post['toid']} AND receive = {$post['fromid']}")
                ->whereOr("send = {$post['fromid']} AND source_cuid = {$post['toid']}")
                ->page($post['page'],10)->order('send_time desc')->select();
            $data = array_reverse($record->toArray());
            if (!empty($data)) {
                return $this->responseSuccess(['data'=>$data]);
                /*return json([
                    'code' => 200,
                    'data' => $data
                ]);*/
            } else {
                return $this->responseFails([]);
                /*return json([
                    'code' => 300,
                    'data' => []
                ]);*/
            }
        }
    }
}
